#include "widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, QOverload<>::of(&Widget::update));
    timer->start(1000);
}

Widget::~Widget()
{
}

void Widget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    drawClock(painter);
}

void Widget::drawClock(QPainter &painter)
{
    // 设置抗锯齿和中心点
    painter.setRenderHint(QPainter::Antialiasing);
    int side = qMin(width(), height());
    painter.translate(width()/2, height()/2);
    painter.scale(side/200.0, side/200.0);

    // 绘制表盘
    painter.setPen(Qt::black);
    painter.setBrush(Qt::white);
    painter.drawEllipse(-90, -90, 180, 180);

    // 绘制刻度
    for(int i = 0; i < 60; i++){
        if(i % 5 ==0){
            painter.setPen(Qt::black);
            painter.drawLine(0, -80, 0, -70);   // 长刻度：10个像素
        }else{
            painter.setPen(Qt::gray);
            painter.drawLine(0, -80, 0, -75);   // 短刻度：5个像素
        }
        painter.rotate(6.0);    // 360° / 60 = 6°
    }

    // 绘制数字
    painter.setPen(Qt::black);
    for(int i = 1; i <= 12; i++){
        painter.save();
        painter.rotate(30.0 * i);   // 顺时针转30°
        painter.translate(0, -60);
        painter.drawText(-10, -10, 20, 20, Qt::AlignCenter, QString::number(i));
        painter.restore();
    }

    // 获取当前事件
    QTime time = QTime::currentTime();

    // 绘制时针
    painter.save();
    painter.setPen(Qt::black);
    painter.setBrush(Qt::black);
    painter.rotate(30.0 * (time.hour() + time.minute() / 60.0)); // 时针角度
    painter.drawConvexPolygon(QPolygon() << QPoint(0, 0) << QPoint(-5, -10) << QPoint(0, -50) << QPoint(5, -10));
    painter.restore();

    // 绘制分针
    painter.save();
    painter.setPen(QColor(0, 0, 139));
    painter.setBrush(QColor(0, 0, 139));
    painter.rotate(6.0 * (time.minute() + time.second() / 60.0)); // 分针角度
    painter.drawConvexPolygon(QPolygon() << QPoint(0, 0) << QPoint(-4, -8) << QPoint(0, -70) << QPoint(4, -8));
    painter.restore();

    // 绘制秒针
    painter.save();
    painter.setPen(QColor(100, 149, 237));
    painter.setBrush(QColor(100, 149, 237));
    painter.rotate(6.0 * time.second()); // 秒针角度
    painter.drawConvexPolygon(QPolygon() << QPoint(0, 0) << QPoint(-2, -5) << QPoint(0, -80) << QPoint(2, -5));
    painter.restore();
}

